package com.thinkcube.edutainment.fragment;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.Util;
import com.thinkcube.edutainment.client.CourseClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.Coupon;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.data.CourseData;
import com.thinkcube.edutainment.domain.data.PaymentData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.domain.dto.PaymentDto;
import com.thinkcube.edutainment.service.SPreferences_;

@EFragment
public class PaymentPlanFragment extends Fragment implements
		OnCheckedChangeListener, OnEditorActionListener {

	@ViewById(R.id.confrim_btn)
	Button confrim;

	@ViewById(R.id.rel_frme)
	FrameLayout summeryFram;

	@ViewById(R.id.instalment_plan_rb)
	RadioGroup instalmentPlan;

	@ViewById(R.id.payment_type)
	RadioGroup paymentType;

	@ViewById(R.id.payment_plan_view)
	RelativeLayout pPlanv;

	@ViewById(R.id.daily_instalment_lb)
	TextView priceLb;

	@ViewById(R.id.daily_instalment)
	TextView price;

	@ViewById(R.id.payment_mode)
	TextView payMode;

	@ViewById(R.id.payment_mode_lb)
	TextView payModelb;

	@ViewById(R.id.payment_plan_lb)
	TextView pPlanLb;

	@ViewById(R.id.payment_plan)
	TextView pPlan;

	@ViewById(R.id.instalment_lb)
	TextView pInstallLb;

	@ViewById(R.id.instalments)
	TextView pInstallment;

	@ViewById(R.id.v_line)
	View vline;

	@ViewById(R.id.coupon_code)
	EditText coupon;

	@ViewById(R.id.payment_type_title)
	TextView paymentTypeTitle;

	@ViewById(R.id.progressBar)
	ProgressBar progress;

	@ViewById(R.id.coupon_hint)
	TextView couponHint;
	
	@ViewById(R.id.discount)
	TextView discount;
	
	@ViewById(R.id.discount_lb)
	TextView discountLb;

	PaymentData paymentData;
	String paymentPlan;
	String paymentMethod;
	PaymentDto paymentDto = new PaymentDto();
	CourseData courseData;
	
	String lastPrice;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments().containsKey("paymentData")) {

			paymentData = getArguments().getParcelable("paymentData");
		}
		if (getArguments().containsKey("courseObject")) {

			courseData = getArguments().getParcelable("courseObject");
			System.out.println("Plan " + courseData.getSubscription_plan());

		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.payment_plan, container, false);

		return view;

	}

	@AfterViews
	void initViews() {
		paymentType.setOnCheckedChangeListener(this);
		instalmentPlan.setOnCheckedChangeListener(this);
		coupon.setOnEditorActionListener(this);
		/* do not display payment plan if subcription plan=2 */
		intiUiSubcriptionPlan();

	}

	@Click(R.id.confrim_btn)
	void confrimBtnClick() {
		
		if(paymentDto.getPaymentPlan()!=null){
		
			FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();
			Bundle bundle = new Bundle();
			paymentDto.setCouponId(coupon.getText().toString());
			bundle.putParcelable("paymentData", paymentData);
			bundle.putParcelable("paymentDto", paymentDto);
			bundle.putParcelable("courseObject", courseData);
			bundle.putString("mode", payMode.getText().toString());
			bundle.putString("plan", pPlan.getText().toString());
			bundle.putString("#installment", pInstallment.getText().toString());
			bundle.putString("price", price.getText().toString());
			bundle.putString("type", "course");
			PaymentConfrimationFragment paymentplan = new PaymentConfrimationFragment_();
			paymentplan.setArguments(bundle);
			fragmentTransaction.replace(R.id.payment_details, paymentplan);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();
		
		}else
		{
			showMessge("Please select a payment plan.");
		}
		
	}

	/* close payment screen when click on cancel button */
	@Click(R.id.cancel_btn)
	void cancelBtnClick() {
		getActivity().finish();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedid) {

		switch (checkedid) {
		case R.id.full_payment:
			
			fullPaymentchecked();
			break;

		case R.id.installments:
			installmentPaymentChecked();

			break;

		case R.id.dailly:
			System.out.println("dailly" +paymentData.getDailyPrice() );
			// intiUiSubcriptionPlan();
			paymentDto.setPaymentPlan("2");
			System.out.println("Daily instalment "
					+ paymentData.getDailyInstallment());

			paymentPlanChecked("Dailly", paymentData.getDailyInstallment());

			// paymentPlanChecked("Dailly","30");
			//paymentDto.setPaymentMethod("1");
			if (paymentData.getDailyPrice() != null) {

				price.setText( "LKR "+Util.numberFormat(paymentData.getDailyPrice()));
				
				priceLb.setText(getResources().getString(
						R.string.daily_installment));
			}

			// paymentMethod="1";
			break;
		case R.id.weekly:
			// intiUiSubcriptionPlan();
			paymentDto.setPaymentPlan("3");

			paymentPlanChecked("Weekly", paymentData.getWeeklyInstallment());

			// paymentPlanChecked("Weekly","4");
			// paymentMethod="2";
			//paymentDto.setPaymentMethod("2");
			if (paymentData.getWeeklyPrice() != null) {
				price.setText("LKR "+ Util.numberFormat(paymentData.getWeeklyPrice()));
				priceLb.setText(getResources().getString(
						R.string.weekly_installment));
			}
			break;
		case R.id.monthly:
			// intiUiSubcriptionPlan();
			paymentDto.setPaymentPlan("4");

			paymentPlanChecked("Monthly", paymentData.getMonthlyInstallment());

			
			if (paymentData.getMonthlyPrice() != null) {

				price.setText("LKR "+ Util.numberFormat(paymentData.getMonthlyPrice()));
				priceLb.setText(getResources().getString(
						R.string.monthly_installment));
			}
			break;

		default:
			break;
		}
	}

	void fullPaymentchecked() {
		priceLb.invalidate();
		priceLb.setText(getResources().getString(R.string.total));
		
		
		
		System.out.println("PRICELB TEXT"+priceLb.getText().toString());
		
	    System.out.println("PRICELB VISIBILITY "+priceLb.getVisibility());
		
		System.out.println("FULLPAYMENT CHECKED");
		if (pPlanv.getVisibility() == View.VISIBLE) {
			pPlanv.setVisibility(View.GONE);
		}
		

		paymentDto.setPaymentPlan("1");
		payMode.setText("Full Payment");
		priceLb.setText(getResources().getString(R.string.total));
	
		
		summeryFram.setVisibility(View.VISIBLE);
		summeryFram.setPadding(0, 0, 0, 50);
		hideSummeryData();
		
		
		if (courseData.getCoursePrice() != null) {
			price.setText("LKR "+Util.numberFormat(courseData.getCoursePrice()));
		}
		priceLb.setPadding(0, 0, 60, 0);

		for (int i = 0; i < ((ViewGroup) instalmentPlan).getChildCount(); ++i) {
			View nextChild = ((ViewGroup) instalmentPlan).getChildAt(i);
			if (nextChild instanceof RadioButton) {
				((RadioButton) nextChild).setChecked(false);
			}
		}
		priceLb.setText(getResources().getString(R.string.total));
		

	}

	void installmentPaymentChecked() {
		if (pPlanv.getVisibility() == View.GONE) {
			payMode.setText("Installment");
			pPlanv.setVisibility(View.VISIBLE);
			summeryFram.setVisibility(View.INVISIBLE);
		}

		summeryFram.setPadding(0, 0, 0, 0);
	}

	void hideSummeryData() {
		pPlanLb.setVisibility(View.GONE);
		pPlan.setVisibility(View.GONE);
		pInstallLb.setVisibility(View.GONE);
		pInstallment.setVisibility(View.GONE);
		android.view.ViewGroup.LayoutParams parm = vline.getLayoutParams();
		parm.height = 60;
		vline.setLayoutParams(parm);
	}

	void showSummeryData() {
		summeryFram.setVisibility(View.VISIBLE);
		pPlanLb.setVisibility(View.VISIBLE);
		pPlan.setVisibility(View.VISIBLE);
		pInstallLb.setVisibility(View.VISIBLE);
		pInstallment.setVisibility(View.VISIBLE);

	}

	void paymentPlanChecked(String pPlanText, String noOfInstallment) {
		showSummeryData();
		pPlan.setText(pPlanText);

		if (noOfInstallment != null) {
			pInstallment.setText(noOfInstallment);
		}

		android.view.ViewGroup.LayoutParams parm = vline.getLayoutParams();
		parm.height = 165;
		vline.setLayoutParams(parm);
	}

	/* check course subcription plan and change UI accordingly */
	void intiUiSubcriptionPlan() {
		if (courseData != null) {
			if (courseData.getSubscription_plan().equals("2")) {
				paymentTypeTitle.setVisibility(View.INVISIBLE);
				paymentType.setVisibility(View.INVISIBLE);
				pPlanv.setVisibility(View.VISIBLE);
				System.out.println("SUBCRIPSTION PALN :2");

			}
		}
	}

	@Bean
	OAuthDto oAuthDto;

	@RestService
	UserClient userClient;

	@RestService
	CourseClient courseClient;

	@Pref
	SPreferences_ pref;

	@Trace
	// @AfterViews
	@Background
	void gettoken(final String couponcode) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					validateCoupon(couponcode,
							userClient.getRequestToken(oAuthDto
									.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});
	}

	@Background
	void validateCoupon(final String couponcode, OAuth requestToken) {

		paymentDto.setAuthToken(requestToken.getoAuth().getToken());
		paymentDto.setUserId(pref.getId().get());

		paymentDto.setItemType("course");
		paymentDto.setItemId(courseData.getCourseId());
		paymentDto.setCouponCode(couponcode);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					validateCouponUi(courseClient.validateCoupon(paymentDto
							.getMultiValuedMap()));

				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@UiThread
	void validateCouponUi(Coupon validateCoupon) {

		Log.v("COUPON VALIDATE MSG", validateCoupon.getMessageText());
		
//		System.out.println("COUPON fff"+validateCoupon.getCoupon()
//					.getDiscountPercentage());
		progress.setVisibility(View.GONE);
		couponHint.setText(validateCoupon.getMessageText());
		couponHint.setVisibility(View.VISIBLE);
		if (validateCoupon.getCoupon() != null) {
			
			if(validateCoupon.getCoupon()
					.getDiscountPercentage()!=null){

			Integer deductedValue = Integer.valueOf(validateCoupon.getCoupon()
					.getDiscountPercentage());
			
			Integer multipluer = 100 - deductedValue;

			//Integer priceInt = Integer.valueOf(price.getText().toString());
			Float priceInt = Float.valueOf(courseData.getCoursePrice());

			Double caclulatedValue = (double) ((priceInt * multipluer) / 100);
			
			discountLb.setVisibility(View.VISIBLE);
			
			discount.setVisibility(View.VISIBLE);
			String.format("%.2f", caclulatedValue);
			discount.setText(String.valueOf((deductedValue*priceInt)/100));
			
			//price.setText(String.valueOf(caclulatedValue));
			
			price.setText(String.format("%.2f", caclulatedValue));

			paymentDto.setCouponCode(validateCoupon.getCoupon().getCouponCode());
			paymentDto.setCouponId(validateCoupon.getCoupon().getCouponId());
			
			
			android.view.ViewGroup.LayoutParams parm = vline.getLayoutParams();
			parm.height = 160;
			vline.setLayoutParams(parm);
			
			}
			else{
				
			}

		}
		else
		{
			/*time base coupons.all process handle from server side*/
			
			
		}

	}

	@UiThread
	void showMessge(final String msg) {

		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	@Bean
	CourseDto courseDto;

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_DONE) {
			Log.v("COUPON CODE ", v.getText().toString());
			gettoken(v.getText().toString());

			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

			couponHint.setVisibility(View.GONE);
			progress.setVisibility(View.VISIBLE);

			return true;
		}
		return false;
	}

}
